package edu.upc.fib.lamsandroid.client.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.UncachedSpiceService;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import edu.upc.fib.lamsandroid.client.LamsAndroidClientApplication;
import edu.upc.fib.lamsandroid.client.R;
import edu.upc.fib.lamsandroid.client.dialog.ConfirmBoxDialog;
import edu.upc.fib.lamsandroid.client.dialog.MessageBoxDialog;
import edu.upc.fib.lamsandroid.client.request.user.LoginRequest;
import edu.upc.fib.lamsandroid.client.request.user.LogoutRequest;
import edu.upc.fib.lamsandroid.server.api.response.Response;
import edu.upc.fib.lamsandroid.server.api.response.user.LoginResponse;
import edu.upc.fib.lamsandroid.server.api.response.user.LogoutResponse;

public class MainActivity extends AbstractBaseActivity {

    private SpiceManager spiceManager = new SpiceManager(UncachedSpiceService.class);

    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private boolean isClosing;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.main);

        isClosing = false;

        initUIComponents();
        setProgressBarIndeterminateVisibility(false);

        if(LamsAndroidClientApplication.getInstance().isLogoutRequested()) {
            doLogout();
            LamsAndroidClientApplication.getInstance().setLogoutRequested(false);
        }
    }

    @Override
    public void onStart() {
        spiceManager.start(this);
        super.onStart();
    }

    @Override
    public void onStop() {
        spiceManager.shouldStop();
        super.onStop();
    }

    private void initUIComponents() {
        etUsername = (EditText) findViewById(R.id.editTextUsername);
        etPassword = (EditText) findViewById(R.id.editTextPassword);
        btnLogin = (Button) findViewById(R.id.buttonLogin);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnLogin.setEnabled(false);

                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();

                doLogin(username, password);
            }
        });

        Button btnExit = (Button) findViewById(R.id.buttonExit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isClosing = true;
                new ConfirmBoxDialog(MainActivity.this, new ConfirmBoxDialog.ConfirmBoxDialogListener() {
                    @Override
                    public void onAccept() {
                        System.exit(0);
                    }

                    @Override
                    public void onDeny() {
                        if(isClosing) {
                            isClosing = false;
                        } else { // logout
                            btnLogin.setEnabled(true);
                        }
                    }
                }).show("Do you really want to exit?");
            }
        });
    }

    private void doLogin(String username, String password) {
        MainActivity.this.setProgressBarIndeterminateVisibility(true);

        LoginRequest loginRequest = new LoginRequest(username, password);
        spiceManager.execute(loginRequest, new RequestListener<LoginResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                MainActivity.this.setProgressBarIndeterminateVisibility(false);
                btnLogin.setEnabled(true);

                new MessageBoxDialog(MainActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(LoginResponse loginResponse) {
                MainActivity.this.setProgressBarIndeterminateVisibility(false);

                switch(loginResponse.getCode()) {
                    case Response.OPERATION_SUCCESSFUL:
                        startActivity(new Intent(MainActivity.this, LessonListActivity.class));
                        finish();
                        break;
                    case LoginResponse.ALREADY_LOGGED:
                        new MessageBoxDialog(MainActivity.this).show("Already logged. Performing a logout.");
                        doLogout();
                        break;
                    case LoginResponse.WRONG_CREDENTIALS:
                        new MessageBoxDialog(MainActivity.this).show("Wrong credentials provided. Please try again.");
                        btnLogin.setEnabled(true);
                        break;
                }
            }
        });
    }

    private void doLogout() {
        MainActivity.this.setProgressBarIndeterminateVisibility(true);

        LogoutRequest logoutRequest = new LogoutRequest();
        spiceManager.execute(logoutRequest, new RequestListener<LogoutResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                MainActivity.this.setProgressBarIndeterminateVisibility(false);
                btnLogin.setEnabled(true);

                new MessageBoxDialog(MainActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(LogoutResponse loginResponse) {
                MainActivity.this.setProgressBarIndeterminateVisibility(false);
                btnLogin.setEnabled(true);
            }
        });
    }

    @Override
    public void onBackPressed() {
        /*
        isClosing = true;
        new ConfirmBoxDialog(this).show("Close application?");
        */
    }

}
